package com.xiaocz.hblsubstitutedriving.activities.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;
import com.xiaocz.common.Common;
import com.xiaocz.common.http.AsyncHttpPostFormData;
import com.xiaocz.common.http.AsyncHttpResponse;
import com.xiaocz.common.http.AsyncOkHttpClient;
import com.xiaocz.common.http.AsyncResponseHandler;
import com.xiaocz.common.model.RspModel;
import com.xiaocz.common.utils.AccountManagers;
import com.xiaocz.common.utils.SPUtil;
import com.xiaocz.hblsubstitutedriving.App;
import com.xiaocz.hblsubstitutedriving.MainActivity;
import com.xiaocz.hblsubstitutedriving.R;
import com.xiaocz.hblsubstitutedriving.base.BaseActivity;
import com.xiaocz.hblsubstitutedriving.model.UserInfo;
import com.xiaocz.hblsubstitutedriving.utils.Constants;
import com.xiaocz.hblsubstitutedriving.widget.ClearTextIconEditText;

import java.io.IOException;
import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.root_layout)
    RelativeLayout rootLayout;
    @BindView(R.id.ed_name)
    public ClearTextIconEditText edName;
    @BindView(R.id.ed_pwd)
    public ClearTextIconEditText edPwd;
    @BindView(R.id.ck_auto_login)
    public CheckBox ckAutoLogin;
    @BindView(R.id.ck_remember_pwd)
    public CheckBox cbRememb;
    @BindView(R.id.btn_login)
    Button buttonLogin;
    @BindView(R.id.tv_content)
    TextView tv_content;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    private boolean autoLogin, rememberPwd;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_login;
    }

    public static void show(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @OnClick({R.id.btn_login, R.id.btn_order, R.id.update_pwd, R.id.btn_register, R.id.tv_content})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                onCheck();
                break;
            case R.id.btn_order:
                break;
            case R.id.btn_register:
                RegisterActivity.show(mContext);
                break;
            case R.id.update_pwd://忘记密码
                ForgetPwdActivity.show(mContext);
                break;
            case R.id.tv_content:
                WebViewActivity.show(mContext, Common.Constant.API_H5 + "Driver/RegisterAgreement");
                break;
        }
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.trans).init();
    }

    @Override
    protected void initWidgets() {
        ImmersionBar.setTitleBar(this, findViewById(R.id.top_view));
        //addLayoutListener(rootLayout, buttonLogin);
        tv_content.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tv_content.getPaint().setAntiAlias(true);//抗锯齿
    }

    @Override
    protected void onResume() {
        edName.setMaxLength(edName, 11, "手机号");
        try {
            ckAutoLogin.setChecked(Boolean.parseBoolean(String.valueOf(SPUtil.get(Common.Static.auto_login, false))));
            cbRememb.setChecked(Boolean.parseBoolean(String.valueOf(SPUtil.get(Common.Static.remember_pwd, false))));
            Object name = SPUtil.get(Common.Static.name_key, "");
            Object pwd = SPUtil.get(Common.Static.pwd_key, "");
            if (name != null) {
                edName.setText(name.toString());
            }
            if (pwd != null) {
                edPwd.setText(pwd.toString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        tvVersion.setText(String.valueOf("当前版本" + getVersionName()));
        super.onResume();
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 10) {
//            if (Build.VERSION.SDK_INT >= 23) {
//                if (!Settings.canDrawOverlays(this)) {
//                    // SYSTEM_ALERT_WINDOW permission not granted...
//                    Toast.makeText(LoginActivity.this,"not granted",Toast.LENGTH_SHORT);
//                }
//            }
//        }
//    }

    @OnCheckedChanged({R.id.ck_auto_login, R.id.ck_remember_pwd})
    public void OnCheckedChangeListener(CompoundButton view, boolean isCheck) {
        switch (view.getId()) {
            case R.id.ck_auto_login://自动登录
                autoLogin = isCheck;
                cbRememb.setChecked(true);
                break;
            case R.id.ck_remember_pwd://记住密码
                rememberPwd = isCheck;
                break;
        }
    }

    @OnCheckedChanged({R.id.cb_clause})
    public void OnCheckedChangeListenerTK(CompoundButton view, boolean isCheck) {
        switch (view.getId()) {
            case R.id.cb_clause:
                if (isCheck) {
                    buttonLogin.setBackground(ContextCompat.getDrawable(mContext, R.drawable.selector_btn_bg));
                    buttonLogin.setEnabled(true);
                } else {
                    buttonLogin.setBackground(ContextCompat.getDrawable(mContext, R.drawable.selector_btn_off_bg));
                    buttonLogin.setEnabled(false);
                }
                break;
        }
    }

    /**
     * 用户名密码判断
     */
    private void onCheck() {
        String valueName = String.valueOf(edName.getText()).trim();
        String valuePwd = String.valueOf(edPwd.getText()).trim();
        if (TextUtils.isEmpty(valueName)) {
            App.getInstance().showMessage(getResources().getString(R.string.message_name));
            return;
        }
        if (TextUtils.isEmpty(valuePwd)) {
            App.getInstance().showMessage(getResources().getString(R.string.message_pwd));
            return;
        }
        if (valuePwd.length() <= 5) {
            App.getInstance().showMessage(getResources().getString(R.string.message_pwd_length));
            return;
        }
        SPUtil.put(Common.Static.auto_login, autoLogin);
        SPUtil.put(Common.Static.remember_pwd, rememberPwd);
        if (autoLogin) {
            SPUtil.put(Common.Static.name_key, valueName);
            SPUtil.put(Common.Static.pwd_key, valuePwd);
        } else {
            if (rememberPwd) {
                SPUtil.put(Common.Static.name_key, valueName);
                SPUtil.put(Common.Static.pwd_key, valuePwd);
            } else {
                SPUtil.put(Common.Static.pwd_key, "");
            }
        }
        onLogin(valueName, valuePwd);
    }

    /**
     * 用户登录
     *
     * @param phone 用户名
     * @param pwd   密码
     */
    private void onLogin(String phone, String pwd) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("phone", phone);
        asyncHttpPostFormData.addFormData("pwd", pwd);
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/driverLogin", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                App.getInstance().showMessage(getResources().getString(R.string.connection_error));
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<UserInfo>>() {
                }.getType();
                RspModel<UserInfo> rspModel = getAnalysis(response, type, "用户登录");
                if (rspModel == null) {
                    return;
                }
                switch (rspModel.getCode()) {
                    case 200:
                        if (rspModel.isStatus() && rspModel.getData() != null && !"".equals(rspModel.getData().toString())) {//保存用户
                            if (rspModel.getData().getAuthentication() == 1) {
                                if (rspModel.getData().getToken() == null || "".equals(rspModel.getData().getToken())) {
                                    dialogLogin(rspModel);
                                } else if (Constants.getUniquePsuedoID().equals(rspModel.getData().getToken())) {
                                    AccountManagers.login(rspModel.getData().getId(), rspModel.getData().getPhone(), new Gson().toJson(rspModel.getData()));
                                    SPUtil.put("TERMINAL_ID", rspModel.getData().getTerminalId());
                                    MainActivity.show(mContext);
                                    finish();
                                } else {
                                    App.getInstance().showMessage("该账号不支持在本部手机登陆，请在上一次登陆的手机登陆使用");
                                }
                            } else {
                                AccountManagers.login(rspModel.getData().getId(), rspModel.getData().getPhone(), new Gson().toJson(rspModel.getData()));
                                SPUtil.put("TERMINAL_ID", rspModel.getData().getTerminalId());
                                MainActivity.show(mContext);
                                finish();
                            }

                        } else {
                            App.getInstance().showMessage(rspModel.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModel.getMessage());
                        break;
                }
            }
        });
    }

    /**
     * 绑定提示
     */
    private void dialogLogin(final RspModel<UserInfo> rspModel) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("登录提示");
        builder.setCancelable(false);
        builder.setMessage("师傅您好，本次登陆后，将自动绑定本手机硬件，无法在其他手机中登陆，如需更换手机需与司管联系解绑。");
        builder.setNegativeButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                onToken(rspModel);
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    /**
     * 绑定设备
     */
    private void onToken(final RspModel<UserInfo> rspModel) {
        loadingDialogShow(false);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("id", rspModel.getData().getId());
        asyncHttpPostFormData.addFormData("token", Constants.getUniquePsuedoID());
        okHttpClient.post(Common.Constant.API_IP + "api/Driver/driverBind", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<String>>() {
                }.getType();
                RspModel<String> rspModelValue = getAnalysis(response, type, "绑定设备");
                if (rspModelValue == null) {
                    return;
                }
                switch (rspModelValue.getCode()) {
                    case 200:
                        if (rspModelValue.isStatus()) {
                            AccountManagers.login(rspModel.getData().getId(), rspModel.getData().getPhone(), new Gson().toJson(rspModel.getData()));
                            SPUtil.put("TERMINAL_ID", rspModel.getData().getTerminalId());
                            MainActivity.show(mContext);
                            finish();
                        } else {
                            App.getInstance().showMessage(rspModelValue.getMessage());
                        }
                        break;
                    default:
                        App.getInstance().showMessage(rspModelValue.getMessage());
                        break;
                }
            }
        });
    }
}
